package com.llc.mall.user.application.command.service.impl;

import com.llc.mall.common.security.AuthUserContext;
import com.llc.mall.user.application.command.service.UserAppService;
import com.llc.mall.user.application.command.commands.ModifyUserCmd;
import com.llc.mall.user.application.command.commands.UserRegisterCmd;
import com.llc.mall.user.domain.share.Token;
import com.llc.mall.user.domain.user.entity.User;
import com.llc.mall.user.domain.gateway.AccountGateway;
import com.llc.mall.user.domain.user.objectvalue.UserProfile;
import com.llc.mall.user.domain.user.repository.UserRepository;
import com.llc.mall.user.domain.user.service.UserDomainService;
import com.llc.mall.user.interfaces.vo.TokenVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 */
@Slf4j
@Service
public class UserAppServiceImpl implements UserAppService {

    private final UserDomainService userDomainService;

    private final AccountGateway accountGateway;

    private final UserRepository userRepository;

    public UserAppServiceImpl(UserRepository userRepository,
                              UserDomainService userDomainService,
                              AccountGateway accountGateway) {
        this.userDomainService = userDomainService;
        this.accountGateway = accountGateway;
        this.userRepository = userRepository;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public TokenVo register(UserRegisterCmd userRegisterCommand) {
        //注册用户
        Long userId = userDomainService.register(UserProfile.builder()
                .nickName(userRegisterCommand.nickName())
                .password(userRegisterCommand.password())
                .build());
        User user = userRepository.findById(userId);
        //token生成
        Token token = accountGateway.storeToken(user);
        return new TokenVo(token.accessToken(), token.refreshToken(), token.expiresIn());
    }

    @Override
    public void modifyUser(ModifyUserCmd modifyUserCmd) {
        Long userId = AuthUserContext.get().getUserId();
        UserProfile userProfile = UserProfile.builder()
                .nickName(modifyUserCmd.nickName())
                .pic(modifyUserCmd.pic())
                .build();
        userDomainService.modify(userId, userProfile);
    }
}
